﻿using BCCommon;
using BCEntity.IM.CustomService;
using Dapper;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace BCData.IM.CustomerService
{
    public class CustomerServiceData : ICustomerServiceData
    {
        private readonly IDatabaseContext databaseContext;

        public CustomerServiceData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public Task<CustomerServiceEntity> GetCustomerServiceAsync(long adminId)
        {
            string sql = typeof(CustomerServiceEntity).GetSelectSqlByPrimaryKeys();

            return this.databaseContext.Slave.QueryFirstOrDefaultAsync<CustomerServiceEntity>(sql, new { adminId });
        }

        public Task InsertAsync(CustomerServiceEntity entity)
        {
            return this.databaseContext.Master.InsertAsync(entity, this.databaseContext.Transaction);
        }

        public Task UpdateAsync(CustomerServiceEntity entity)
        {
            return this.databaseContext.Master.UpdateAsync(entity, this.databaseContext.Transaction);
        }

        public Task<IEnumerable<CustomerServiceEntity>> GetCustomerServicesAsync(string countyCode)
        {
            const string sql = @"SELECT
    A.AdminId,
    C.FirstLogonTime,
    C.HeartbeatTime,
    IFNULL(C.TotalReceptionCount, 0) TotalReceptionCount,
    IFNULL(C.CurrentReceptionCount, 0) CurrentReceptionCount,
    IFNULL(C.OnlineCount, 0) OnlineCount
FROM Admin A
INNER JOIN StaffOrganizationMappingRecord B ON B.AdminId = A.AdminId
LEFT JOIN customerservice C ON C.AdminId = A.AdminId
WHERE A.AccountStatus = 'Using'
AND B.JobTitleKey = 'StaffTitle_CustomerService_AdminiStration'";

            return this.databaseContext.Slave.QueryAsync<CustomerServiceEntity>(sql, new { CityCode = countyCode.Substring(0, 4) + "00" });
        }

        public Task<CustomerServiceEntity> GetDirectorAsync()
        {
            const string sql = @"SELECT
    A.AdminId,
    C.FirstLogonTime,
    C.HeartbeatTime,
    IFNULL(C.TotalReceptionCount, 0) TotalReceptionCount,
    IFNULL(C.CurrentReceptionCount, 0) CurrentReceptionCount,
    IFNULL(C.OnlineCount, 0) OnlineCount
FROM Admin A
INNER JOIN StaffOrganizationMappingRecord B ON B.AdminId = A.AdminId
LEFT JOIN customerservice C ON C.AdminId = A.AdminId
WHERE A.AccountStatus = 'Using'
AND B.JobTitleKey = 'StaffTitle_Director_AdminiStration' LIMIT 1";

            return this.databaseContext.Slave.QueryFirstOrDefaultAsync<CustomerServiceEntity>(sql);
        }
    }
}
